<?php
/**
 * 财务管理
 * User: @671
 * Date: 2018/8/24 0024
 * Time: 16:34
 */
namespace app\publics\controller;

use think\facade\Request;
use think\Db;
use thinkcms\auth\library\Tree;
use thinkcms\auth\model\Menu;

use app\common\model\OrderModel;
use app\common\model\UserModel;

use app\common\utils\StatusUtils;
use app\service\User as UserService;


class Finance extends Base
{
    protected $ufl_model;

    public function __construct()
    {
        parent::__construct();
        $this->ufl_model = new OrderModel();
        $this->u_model = new UserModel();
    }

    // 充值列表
    public function recharge()
    {
        $param = $this->ufl_model->param_format(input('param.'));

        $map['uf.deal_type'] = ORDER_TYPE_RECHARGE;

        if($param['status'] !=-1){
            $map['uf.status'] = $param['status'];
        }

        if(!empty($param['order_no'])){
            $map['uf.order_no'] = $param['order_no'];
        }

        $count = (int)$this->ufl_model
            ->alias('uf')
            ->Join('p_user u', 'uf.uid = u.uid')
            ->where($map)
            ->count();

        $list  = $this->ufl_model
            ->alias('uf')
            ->Join('p_user u', 'uf.uid = u.uid')
            ->where($map)
            ->field('uf.*, u.uid,u.phone,u.username')
            ->order('uf.create_time desc')
            ->paginate($param['limit'], $count);

        $select_list = [];
        foreach (StatusUtils::$arr as $k => $v) {
            $select_list[$k] = explode('：', $v)[0];
        }

        $cur_page_sum = 0;
        foreach ($list as $k => $v) {
            $cur_page_sum += $v['deal_amount'];
        }
        $all_page_sum = $this->ufl_model
            ->alias('uf')
            ->Join('p_user u', 'uf.uid = u.uid')
            ->where($map)
            ->sum('uf.deal_amount');


        $this->assign([
            'param' => $param,
            'list'  => $list,
            'cur_page_sum' =>$cur_page_sum,
            'all_page_sum' =>$all_page_sum,
            'select_list' => $select_list,
            'limit' => select_limit($param['limit']),
            'count' => $count,
            'page'  => $list->render()
        ]);
        return $this->fetch();
    }

    // 提现列表
    public function withdrawal()
    {
        $param = $this->ufl_model->param_format(input('param.'));

        $map['uf.deal_type'] = ORDER_TYPE_WITHDRAWAL;

        if($param['status'] !=-1){
            $map['uf.status'] = $param['status'];
        }

        if(!empty($param['order_no'])){
            $map['uf.order_no'] = $param['order_no'];
        }

        $count = (int)$this->ufl_model
            ->alias('uf')
            ->Join('p_user u', 'uf.uid = u.uid')
            ->where($map)
            ->count();

        $list  = $this->ufl_model
            ->alias('uf')
            ->Join('p_user u', 'uf.uid = u.uid')
            ->where($map)
            ->field('uf.*, u.uid,u.phone,u.username')
            ->order('uf.create_time asc')
            ->paginate($param['limit'], $count);

        $select_list = [];
        foreach (StatusUtils::$arr as $k => $v) {
            $select_list[$k] = explode('：', $v)[0];
        }
        $cur_page_sum = 0;
        foreach ($list as $k => $v) {
            $cur_page_sum += $v['deal_amount'];
        }
        $all_page_sum = $this->ufl_model
            ->alias('uf')
            ->Join('p_user u', 'uf.uid = u.uid')
            ->where($map)
            ->sum('uf.deal_amount');
        $this->assign([
            'param' => $param,
            'list'  => $list,
            'cur_page_sum' =>$cur_page_sum,
            'all_page_sum' =>$all_page_sum,
            'select_list' => $select_list,
            'limit' => select_limit($param['limit']),
            'count' => $count,
            'page'  => $list->render()
        ]);
        return $this->fetch();
    }

    // 审核订单
    public function audit()
    {
        $id = input('param.id');
        if (Request::isPost()) {
            $post = input('post.');
            $user = new UserModel;
            $uService = new UserService;

            $order_list = $this->ufl_model->where('id',$post['id'])->field('uid,deal_amount,deal_after,status')->find();
            if($order_list['status'] ==1 ){
                $this->error('审核已通过，请勿重新审核',url('recharge'));
            }
            foreach (StatusUtils::$arr as $k => $v) {
                if($post['status_name'] == $v){
                    $status = $k;
                }
            }
            if ($status == 0) {
                // 未审核
               $this->error('默认审核状态无法更改');
            }
            if ($status == 1) {
                // 审核通过
                // 更改状态->用户余额增加
                $balance = $order_list['deal_amount'];
                $info_ufl = $this->ufl_model->where('id',$post['id'])
                    ->update(['status' => $status]);
                if($info_ufl) {
                    $info = $user->where('uid',$order_list['uid'])
                        ->setInc('balance', $balance);

                    $msg = "充值{$balance}个砖石成功！";
                    $uService->sendEmailToUid($order_list['uid'], $msg);
                }

            }
            if ($status == 2) {
                // 拒绝审核
                $info_ufl = $this->ufl_model->where('id',$post['id'])->update(['status' => $status]);
            }
            $this->success('提交成功',url('recharge'));
        }
        $this->assign([
            'id' => $id,
            'list'=>StatusUtils::$arr,
            'tips'=>StatusUtils::$arr,
            'status' => $this->ufl_model->getFieldById($id, 'status')
        ]);
        return $this->fetch();
    }

    //批量审核
    public function status_update()
    {
        $post = input('post.');

        if (empty($post['id'])) {
            $this->error('至少选择一个用户');
        }

        $data = [];
        $update = [];
        $log_order = [];
        $ids  = explode(',', $post['id']);
        foreach ($ids as $k => $v) {

            $order_list = $this->ufl_model->where('id',$v)->field('uid,deal_after,status,order_no')->find();
            $id = $this->u_model->where('uid',$order_list['uid'])->value('id');

            if($order_list['status'] == 1 ){
                $this->error('请选择未审核订单操作',url('recharge'));
            }
            array_push($log_order, [
                'order' => $order_list['order_no'],
            ]);
            array_push($data, [
                'id' => $v,
                'status' => $post['status']
            ]);
            array_push($update, [
                'id' => $id,
                'balance' => $order_list['deal_after']

            ]);
        }

        $info = $this->ufl_model->saveAll($data);
        if (!empty($info)) {
            $title = $post['status'] == 1 ? '审核通过' : '审核不通过';

            if($post['status'] == 1){
                $this->u_model->saveAll($update);
            }
            foreach ($log_order as $key =>$value) {
                $msg = "管理员[ {$this->username} ]修改订单 [ {$value['order']} ]".$title;
                $this->auth->createLog($msg, $title);
            }

            $this->success('操作成功');
        } else {
            $this->error('操作失败，无任何数据变化');
        }
    }

    //删除订单
    public function delete()
    {
        $post = input('param.');

        if (empty($post['id'])) {
            $this->error('至少选择一个用户');
        }

        $this->ufl_model->destroy($post['id']);
        $this->success('删除成功');
    }
}
